package com.caishi.lkx.user.api;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caishi.lkx.common.context.UserContext;
import com.caishi.lkx.exam.records.oss.RecordsOssConfig;
import com.zzw.common.AliyunAuthPlugins;
import com.zzw.common.annotation.ApiResult;
import com.zzw.common.file.OssPlugins;
import com.caishi.lkx.user.model.WeixinCodeModel;
import com.caishi.lkx.user.service.impl.WeixinCodeServiceImpl;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Tag(name = "微信二维码")
@RestController
@RequestMapping("/weixin")
public class WeixinApis {
    @Autowired
    OssPlugins ossPlugins;
    @Autowired
    RecordsOssConfig ossConfig;
    @Autowired
    UserContext userContext;
    @Autowired
    private AliyunAuthPlugins aliyunAuthPlugins;

    @Autowired
    WeixinCodeServiceImpl weixinCodeService;

    private String getFileExtension(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            return null;
        }
        int lastDotIndex = originalFilename.lastIndexOf('.');
        if (lastDotIndex == -1) {
            return ""; // No extension found
        }
        return originalFilename.substring(lastDotIndex + 1);
    }

    @ApiResult
    @PostMapping("/qrcode/upload")
    public boolean uploadQrCode(@RequestParam("url") String url,@RequestParam("name") String name) throws IOException, ClientException {
//        先获取上传路径，前端上传，再调用接口入库


        String userId = userContext.currentUserId();
        QueryWrapper<WeixinCodeModel> queryWrapper = new QueryWrapper();
//        queryWrapper.eq("creator", userId);
        queryWrapper.eq("name", name);
        WeixinCodeModel weixinCode = weixinCodeService.getOne(queryWrapper);



//
//        OssPlugins ossPlugins = OssPluginsAuto.getOssPluginsByType(type);
//        String ossFilePath = ossPlugins.getFilePath(filename);
//        AssumeRoleResponse assumeRoleResponse = aliyunAuthPlugins.stsAuth(Collections.singletonList("oss:*"), Collections.singletonList("acs:oss:*:*:*"), 3600L);
//        Map<String, Object> buildMap = MapUtil.<String, Object>builder()
//                .put("path", ossFilePath)
//                .put("accessKeyId", assumeRoleResponse.getCredentials().getAccessKeyId())
//                .put("accessKeySecret", assumeRoleResponse.getCredentials().getAccessKeySecret())
//                .put("stsToken", assumeRoleResponse.getCredentials().getSecurityToken())
//                .put("bucket", ossPlugins.ossConfig.getBucket())
//                .put("endpoint", ossPlugins.ossConfig.getExtranetEndpoint())
//                .put("region", ossPlugins.ossConfig.getRegion())
//                .build();


        WeixinCodeModel weixinCodeModel = new WeixinCodeModel();
        if (weixinCode == null) {
//        数据库写入
            weixinCodeModel.setCreateTime(new DateTime());
            weixinCodeModel.setUrl(url);
            weixinCodeModel.setCreator(userId);
            weixinCodeModel.setName(name);
            weixinCodeService.save(weixinCodeModel);
        } else {
            weixinCodeModel.setCreateTime(weixinCode.getCreateTime());
            weixinCodeModel.setUrl(url);
            weixinCodeModel.setCreator(weixinCode.getCreator());
            weixinCodeModel.setUpdator(userId);
            weixinCodeModel.setUpdateTime(new DateTime());
            weixinCodeModel.setId(weixinCode.getId());
            weixinCodeModel.setName(name);
            weixinCodeService.saveOrUpdate(weixinCodeModel);
        }
        return true;
    }

    @ApiResult
    @DeleteMapping("/qrcode/delete/{id}")
    public String deleteQrCode(@PathVariable int id) {

        WeixinCodeModel weixinCode = weixinCodeService.getById(id);
        if (weixinCode == null) {
            return "QR code not found";
        }
        boolean b = weixinCodeService.removeById(id);
        // Delete file from OSS
//        OSS client =
//                ossPlugins.createClient();
//        client.deleteObject(ossConfig.getBucket(), weixinCode.getUrl());
//
//        client.shutdown();
        return b + "";
    }
    @ApiResult
    @DeleteMapping("/qrcode/disable/{id}")
    public String disableQrCode(@PathVariable int id) {

        WeixinCodeModel weixinCode = weixinCodeService.getById(id);
        if (weixinCode == null) {
            return "QR code not found";
        }
        if(weixinCode.getEnable()!=null){
            weixinCode.setEnable(!weixinCode.getEnable());
        }else{
            weixinCode.setEnable(true);
        }
        QueryWrapper<WeixinCodeModel> queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",id);
        weixinCodeService.update(weixinCode,queryWrapper);
        // Delete file from OSS
//        OSS client =
//                ossPlugins.createClient();
//        client.deleteObject(ossConfig.getBucket(), weixinCode.getUrl());
//
//        client.shutdown();
        return  "禁用成功";
    }
    @ApiResult
    @GetMapping("/qrcode/list")
    public Page<WeixinCodeModel> getQrCodeList(@RequestParam(value = "page",defaultValue = "1") int page, @RequestParam(value = "size",defaultValue = "10") int size) {
        QueryWrapper<WeixinCodeModel> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("create_time");
        Page page1 = new Page(page, size);

        Page<WeixinCodeModel> weixinCodeModelPage = weixinCodeService.selectPage(page1, queryWrapper);
        return weixinCodeModelPage;

    }

    @ApiResult
    @GetMapping("/qrcode/getRandom")
    public String getRandomQrCode() {
        OSS client =ossPlugins.createClient();
//        client.getObject(ossConfig.getBucket(),)
        QueryWrapper<WeixinCodeModel> queryWrapper = new QueryWrapper();
//        queryWrapper.orderByDesc("RAND()");
//        queryWrapper.last("limit 1");
        queryWrapper.eq("enable",true);
        queryWrapper.select("url");
        List<WeixinCodeModel> list = weixinCodeService.list(queryWrapper);
        if(list.size()==0){
            return "QR code not found";
        }
        int maxId = list.size();
        Random random = new Random();
        int randomId = random.nextInt(maxId);
//        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
//        String res = client.generatePresignedUrl(ossPlugins.ossConfig.getBucket(), weixinCode.getUrl(), expiration).toString().replace("http", "https");
        return list.get(randomId).getUrl();
    }
    @ApiResult
    @GetMapping("/qrcode/getUrl")
    public String getUrl(@RequestParam(value = "id") int id) {
        OSS client =ossPlugins.createClient();
//        client.getObject(ossConfig.getBucket(),)
        QueryWrapper<WeixinCodeModel> queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", id);
        WeixinCodeModel weixinCode = weixinCodeService.getOne(queryWrapper);

        if (weixinCode == null) {
            return "QR code not found";
        } else {
//            Date expiration = new Date(new Date().getTime() + 3600 * 1000);
//            String res = client.generatePresignedUrl(ossPlugins.ossConfig.getBucket(), weixinCode.getUrl(), expiration).toString().replace("http", "https");
            return weixinCode.getUrl();

//            return "http://"+ossConfig.getExtranetEndpoint()+"/"+weixinCode.getUrl();
        }
    }

}
